<template>
  <div>
    <div class="__table">
      <el-button @click="dialogOpen('add')"
                 v-if="!search"
                 class="__table_button"><i class="el-icon-plus"></i></el-button>
      <s-table
        :table="table"
        ref="table"
        :control="false"
        :expand="false"
        :index="true"
        :pagination="false"
        @http="tableWatch">
        <el-table-column
          fixed="right"
          align="center"
          slot="operation"
          class-name="operationMore"
          label="操作"
          v-if="!search"
          width="120">
          <template scope="s">
            <el-button type="success" icon="el-icon-edit" size="mini" @click="dialogOpen('PUT', s.row, s.$index)"
                       round></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="tableDelete(s.$index, s.row)"
                       round></el-button>
          </template>
        </el-table-column>
      </s-table>
    </div>
    <s-dialog :dialog="dialog">
      <p slot="title">收款人
        <span>收款金额 最大值：{{SplitK(parseFloat(TRAVEL_moneySum || 0) - parseFloat(TRAVEL_moneyUse || 0) + parseFloat(dialog.oldMoney || 0))}}</span>
      </p>
      <s-form :form="formDialog" ref="formDialog">
        <el-row>
          <el-col :xs="24" :lg="{span: 11, offset: 0}">
            <el-form-item prop="payee" label="收款人/供应商 ">
              <el-select v-model="formDialog.payee"
                         filterable
                         remote
                         :remote-method="dialogPayee"
                         ref="payee"
                         @change="dialogPayeeChange"
                         placeholder="请选择">
                <el-option
                  v-for="item in dialog.payee"
                  :key="item.id"
                  :label="item.bxSupplierName + '   ' + item.bxSupplierDepartmentname"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 11, offset: 1}">
            <el-form-item prop="money" label="收款金额 ">
              <el-input-number
                v-model.number="formDialog.money"
                :min="0"
                :max="SplitK(parseFloat(TRAVEL_moneySum || 0) - parseFloat(TRAVEL_moneyUse || 0) + parseFloat(dialog.oldMoney || 0))"
                placeholder="收款金额 "></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 23, offset: 0}">
            <el-form-item prop="bearDepartmentId" label="费用所属部门">
              <el-cascader
                :options="DEPARTMENT.department"
                v-model="formDialog.bearDepartmentId"
                :show-all-levels="false"
                ref="bearDepartmentId"
                clearable
                filterable
                change-on-select
                :props="{
                  value: 'key',
                }"
                placeholder="所属部门"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
  </div>
</template>

<script>
  import {AutoVue, AutoPromise, SplitK, DeepCopy} from '~/plugins/Tools';

  let id = 0;

  /**
   * 报销单明细
   payee  (string, optional): 收款人 $$$true$false$false$$2$vNull,
   departmentId (string, optional): 所属部门 $$$true$false$false$$2$vNull,
   money (string, optional): 收款金额 $$$true$false$false$$2$vNull,
   */
  function __formDialog () {
    return {
      payee: {value: '', rule: ['vNull__change']},
      departmentId: {value: '', rule: ['vNull']},
      money: {value: '', rule: ['vNull']},
      bearDepartmentId: {value: [], rule: ['vNull__change']},
    };
  }

  function tofixed (dt) {
    dt += '';
    let result;
    if (dt.indexOf('.') !== -1) {
      result = dt.substr(0, dt.indexOf('.') + 3);
    } else {
      result = dt;
    }
    return parseFloat(result);
  }

  export default AutoVue({
    name: 'department',
    data: {
      table: {
        column: [
          {
            label: '费用所属部门',
            prop: 'bearDepartmentName',
          },
          {'label': '收款方', 'prop': 'payeeName', 'minWidth': '0px'}, {
            'label': '收款方所属部门 ',
            'prop': 'departmentName',
            'minWidth': '0px',
          }, {'label': '收款金额 ',
            'prop': 'money',
            'minWidth': '0px',
            formatter: (row, column) => {
              return SplitK(row[column.property || column]);
            },
          },
        ],
        key: 'id',
        muti: false,
      },
      formDialog: __formDialog(),
      dialog: {
        modal: false,
        width: '50%',
        row: {},
        title: '新增',
        payee: [],
        bearDepartmentId: [],
        oldMoney: 0,
        index: '',
      },
    },
    props: {
      card: {
        type: Object,
        require: true,
      },
      search: {
        type: Boolean,
        default: false,
      },
      travel: {
        type: Boolean,
        default: false,
      },
      init: {
        type: Array,
      },
    },
    store: ['TRAVEL_moneyUse', 'TRAVEL_moneySum', 'DEPARTMENT'],
    methods: {
      SplitK,
      tableDelete (index, row) {
        let tableRef = 'table';
        this.$confirm('您将删除该条明细。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }).then(async () => {
          this[tableRef].data.splice(index, 1);
          this.SET('TRAVEL_moneyUse', this.TRAVEL_moneyUse - row.money);
        });
      },
      async dialogPayee (query) {
        if (this.card.code === 'borrowing') {
          this.dialog.payee = await this.post('/supplier/get', {
            name: query,
          });
        } else {
          this.dialog.payee = await this.post('/supplier/get', {
            name: query,
          });
        }
      },
      dialogPayeeChange (id) {
        this.dialog.payee.forEach(item => {
          if (item.id === id) {
            this.formDialog.departmentId = item.bxSupplierDepartmentid;
            this.formDialog.departmentName = item.bxSupplierDepartmentname;
          }
        });
      },
      async dialogOpen (type, more, index) {
        if (type) {
          type = type.toUpperCase();
        } else return;
        await AutoPromise([
          async () => {
            this.dialogPayee(more ? more.payeeName : '');
          },
          async () => {
            if (more && !more.bearDepartmentIdOld) {
              more.bearDepartmentIdOld = await this.get('/dictionaries/departmentIds/' + more.bearDepartmentId);
            }
          },
        ]);
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          this.formDialog.id = 0;
          break;
        case 'PUT':
          this.dialog.title = '修改';
          this.AwaitVue('formDialog', () => {
            this.dialog.oldMoney = more.money;
            this.formDialog = {
              ...this.formDialog,
              ...this.ObjectClone(__formDialog(), more),
            };
            this.formDialog.bearDepartmentId = more.bearDepartmentIdOld;
          });
          this.dialog.row = more;
          this.dialog.index = index;
          break;
        }
        this.dialog.visible = true;
      },
      dialogSave () {
        if (parseFloat(this.formDialog.money) === 0) {
          return this.$alert('收款金额不能为0！', '提示');
        }

        this.VALIDATE('formDialog', option => {
          option.id = id++;
          option.payeeName = this.$refs.payee.selectedLabel.split('   ')[0];
          option.bearDepartmentName = this.$refs.bearDepartmentId.currentLabels.join('-');
          option.bearDepartmentIdOld = DeepCopy(option.bearDepartmentId);
          option.bearDepartmentId = option.bearDepartmentId.reverse()[0];

          if (option.money !== 0) {
            option.money = tofixed(option.money);
          }
          if (this.dialog.index === '') {
            this.table.data.push(option);
          } else {
            this.table.data.splice(this.dialog.index, 1);
            this.table.data.unshift(option);
          }
          this.SET('TRAVEL_moneyUse', this.TRAVEL_moneyUse + option.money - this.dialog.oldMoney);
          this.dialog.dialogInit.call(this);
        });
      },
    },
    mounted: function () {
      this.USE('DEPARTMENT');
      if (this.init && this.init.length !== 0) {
        let data = [];
        let oldMoney = 0;
        this.init.forEach(item => {
          data.push({
            ...item,
            oldMoney: item.money,
          });
          oldMoney += parseFloat(item.money);
        });
        this.SET('TRAVEL_moneyUse', oldMoney);
        this.table.data = data;
      }
    },
  });
</script>

<style scoped lang="scss">
  .card {
    float: left;
    border-radius: 3px;
    box-shadow: 0 2px 10px 1px rgba(0, 0, 0, .1);
    height: 110px;
    width: 300px;
    margin: 15px;
    padding: 25px;
    position: relative;
    vertical-align: top;
    transition: .4s;
    cursor: pointer;
    &:hover {
      box-shadow: 0 10px 20px 1px rgba(0, 0, 0, .1);
      text-decoration: none;
    }
  }

  .card__icon {
    font-size: 24px;
    left: 28px;
    position: absolute;
    top: 25px;
    color: #20a0ff;
  }

  .card__title {
    color: #20a0ff;
    margin-top: 0;
    margin-bottom: 10px;
    margin-left: 40px;
  }

  .card__body {
    line-height: 22px;
    margin-left: 40px;
  }

  @media screen and (max-width: 800px) {
    .card {
      width: calc(100% - 80px);
    }
  }
</style>
